package com.common.utils;

import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author 大静
 * @version 1.0
 * @date 2021-05-07 11:22
 * @description Cookie 工具类
 */
public final class CookieUtils {
  private static final Logger log = LoggerFactory.getLogger(CookieUtils.class);
  /**
   * 得到Cookie的值, 不编码
   *
   * @param request 请求
   * @param cookieName cookie key
   * @return cookie value
   */
  public static String getCookieValue(HttpServletRequest request, String cookieName) {
    return getCookieValue(request, cookieName, false);
  }
  /**
   * 得到Cookie的值,
   *
   * @param request 请求
   * @param cookieName cookie key
   * @return cookie value
   */
  public static String getCookieValue(
      HttpServletRequest request, String cookieName, boolean isDecoder) {
    Cookie[] cookieList = request.getCookies();
    if (cookieList == null || cookieName == null) {
      return null;
    }
    String retValue = null;
    try {
      for (Cookie cookie : cookieList) {
        if (cookie.getName().equals(cookieName)) {
          if (isDecoder) {
            retValue = URLDecoder.decode(cookie.getValue(), "UTF-8");
          } else {
            retValue = cookie.getValue();
          }
          break;
        }
      }
    } catch (Exception e) {
      log.error("Cookie Decoder Error", e);
    }
    return retValue;
  }

  /**
   * 得到Cookie的值,
   *
   * @param request 请求
   * @param cookieName cookie key
   * @return cookie value
   */
  public static String getCookieValue(
      HttpServletRequest request, String cookieName, String encodeString) {
    Cookie[] cookieList = request.getCookies();
    if (cookieList == null || cookieName == null) {
      return null;
    }
    String retValue = null;
    try {
      for (Cookie cookie : cookieList) {
        if (cookie.getName().equals(cookieName)) {
          retValue = URLDecoder.decode(cookie.getValue(), encodeString);
          break;
        }
      }
    } catch (Exception e) {
      log.error("Cookie Decoder Error", e);
    }
    return retValue;
  }

  /** 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码 */
  public static void setCookie(
      HttpServletRequest request,
      HttpServletResponse response,
      String cookieName,
      String cookieValue) {
    setCookie(request, response, cookieName, cookieValue, -1);
  }
  /** 设置Cookie的值 在指定时间内生效,但不编码 */
  public static void setCookie(
      HttpServletRequest request,
      HttpServletResponse response,
      String cookieName,
      String cookieValue,
      int cookieMaxage) {
    setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
  }
  /** 设置Cookie的值 不设置生效时间,但编码 */
  public static void setCookie(
      HttpServletRequest request,
      HttpServletResponse response,
      String cookieName,
      String cookieValue,
      boolean isEncode) {
    setCookie(request, response, cookieName, cookieValue, -1, isEncode);
  }
  /** 设置Cookie的值 在指定时间内生效, 编码参数 */
  public static void setCookie(
      HttpServletRequest request,
      HttpServletResponse response,
      String cookieName,
      String cookieValue,
      int cookieMaxage,
      boolean isEncode) {
    setCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
  }
  /** 设置Cookie的值 在指定时间内生效, 编码参数(指定编码) */
  public static void setCookie(
      HttpServletRequest request,
      HttpServletResponse response,
      String cookieName,
      String cookieValue,
      int cookieMaxage,
      String encodeString) {
    setCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
  }

  /** 删除Cookie带cookie域名 */
  public static void deleteCookie(
      HttpServletRequest request, HttpServletResponse response, String cookieName) {
    doSetCookie(request, response, cookieName, "", -1, false);
  }
  /**
   * 设置Cookie的值，并使其在指定时间内生效
   *
   * @param cookieMaxage cookie生效的最大秒数
   */
  private static void doSetCookie(
      HttpServletRequest request,
      HttpServletResponse response,
      String cookieName,
      String cookieValue,
      int cookieMaxage,
      boolean isEncode) {
    try {
      if (cookieValue == null) {
        cookieValue = "";
      } else if (isEncode) {
        cookieValue = URLEncoder.encode(cookieValue, "utf-8");
        Cookie cookie = new Cookie(cookieName, cookieValue);
        if (cookieMaxage > 0) {
          cookie.setMaxAge(cookieMaxage);
        }
        cookie.setPath("/");
        response.addCookie(cookie);
      }
    } catch (Exception e) {
      log.error("Cookie Encode Error", e);
    }
  }
  /**
   * 设置Cookie的值，并使其在指定时间内生效
   *
   * @param cookieMaxage cookie生效的最大秒数
   */
  private static void doSetCookie(
      HttpServletRequest request,
      HttpServletResponse response,
      String cookieName,
      String cookieValue,
      int cookieMaxage,
      String encodeString) {
    try {
      if (cookieValue == null) {
        cookieValue = "";
      } else {
        cookieValue = URLEncoder.encode(cookieValue, encodeString);
        Cookie cookie = new Cookie(cookieName, cookieValue);
        if (cookieMaxage > 0) {
          cookie.setMaxAge(cookieMaxage);
        }
        if (request != null) {
          cookie.setDomain(getDomainName(request));
        }
        cookie.setPath("/");
        response.addCookie(cookie);
      }
    } catch (Exception e) {
      log.error("Cookie Encode Error", e);
    }
  }
  /** 得到cookie的域名 */
  private static String getDomainName(HttpServletRequest request) {
    String domainName = null;
    String serverName = request.getRequestURL().toString();
    if (Strings.isBlank(serverName)) {
      domainName = "";
    } else {
      serverName = serverName.toLowerCase();
      serverName = serverName.substring(7);
      final int end = serverName.indexOf("/");
      serverName = serverName.substring(0, end);
      final String[] domains = serverName.split("\\.");
      int len = domains.length;
      if (len > 3) {
        domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
      } else if (len > 1) {
        domainName = "." + domains[len - 2] + "." + domains[len - 1];
      } else {
        domainName = serverName;
      }
    }
    if (domainName != null && domainName.indexOf(":") > 0) {
      String[] strArray = domainName.split("\\:");
      domainName = strArray[0];
    }
    return domainName;
  }
}
